import ToeUpload from '@/components/UploadDialog/index';
import ToeForm from '@/components/FormDialog/index';
import type { FormItem } from '@/components/FormDialog/data';
import {
  addDriveParaLib,
  delDriveParaLib,
  updateDriveParaLib,
  getDriveParaLibByPage,
  uploadDriveParaLibExcel,
  driveParaLibExcelExport,
} from '@/services/drivepara/driveparalib';
// import { getS210motorList, getV90motorList } from '@/services/sales/salesNeedInfo';
import ProTable from '@ant-design/pro-table';
import { PlusOutlined } from '@ant-design/icons';
// import type { EditableFormInstance } from '@ant-design/pro-components';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import { Button, Form, message, Input, Modal } from 'antd';
import React, { useRef, useState } from 'react';
import { useAccess, useLocation } from 'umi';

// import DebounceSelect from '@/components/DebounceSelect';
// import { Service } from 'umi';

// Usage of DebounceSelect
// interface UserValue {
//   label: string;
//   value: string;
// }

// async function fetchV90motorList(username: string): Promise<UserValue[]> {
//   console.log('fetching user', username);
//   return getV90motorList({ blurry: username }).then((res) => {
//     return res.data.map((item) => {
//       return {
//         label: item.motorOrderNum,
//         value: item.motorOrderNum,
//         rowData: item,
//       };
//     });
//   });
// }

// async function fetchS210motorList(username: string): Promise<UserValue[]> {
//   console.log('fetching user', username);
//   return getS210motorList({ blurry: username }).then((res) => {
//     return res.data.map((item) => {
//       return {
//         label: item.motorOrderNum,
//         value: item.motorOrderNum,
//         rowData: item,
//       };
//     });
//   });
// }

const DriveParaLib: React.FC<{}> = () => {
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  // const [deleteVisit, setDeleteVisit] = useState(false); // 删除提示框
  const [formVisit, setFormVisit] = useState(false); // form表单设置
  // const [formDisabled, setFormDisabled] = useState(false); //设置表单禁用
  const formRef = useRef(null);
  const [formTitle, setFormTitle] = useState('新建驱动参数库'); //
  // const [rowData, setRowData] = useState({ id: '' }); // 保存行值
  const actionRef = useRef<ActionType>();
  // const editorFormRef = useRef<EditableFormInstance<DataSourceType>>();
  const [isCreate, setIsCreate] = useState(false);
  const access = useAccess();

  // const [form] = Form.useForm();
  // const [uploadVisit, setUploadVisit] = useState(false); //上传按钮显示
  // const uploadRef = useRef(null);
  /**
   * 穿梭框的数据设置
   */
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
      align: 'center',
      sorter: true,
    },
    {
      title: '唯一标识', //表头显示的名称
      search: false,
      hideInTable: true,
      dataIndex: 'identification', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      align: 'center',
      sorter: true,
    },
    {
      title: '行业', //表头显示的名称
      dataIndex: 'vm', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路
      align: 'center',
      sorter: true,
      valueType: 'select',
      width: 80,
      valueEnum: {
        1: { text: '电子' },
        2: { text: '电池' },
        3: { text: '物流' },
        4: { text: '汽车' },
        5: { text: '太阳能' },
        6: { text: '增材制造' },
        7: { text: '包装' },
        8: { text: '食品饮料' },
        9: { text: '金属加工' },
        10: { text: '其他' },
      },
    },

    {
      title: '设备名称', //表头显示的名称
      dataIndex: 'deviceName', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      // width: 200,
      align: 'center',
      sorter: true,
    },

    {
      title: '操作',
      align: 'center',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      render: (text, record, _, action) => {
        const buttonList = [];
        if (access.canAdmin() || access.canChiefEngineer()) {
          buttonList.push(
            <a
              key="editable"
              onClick={() => {
                action?.startEditable?.(record.id);
                setIsCreate(false);
              }}
            >
              edit
            </a>,
          );

          buttonList.push(
            <a
              key="deleteKey"
              onClick={() => {
                Modal.confirm({
                  title: 'Delete MRP log',
                  content: 'R u sure to delete MRP log?',
                  okText: 'Yes',
                  cancelText: 'No',
                  onOk: async () => {
                    await delDriveParaLib({ id: record.id });
                    actionRef.current?.reload();
                  },
                });
              }}
            >
              delete
            </a>,
          );
        }

        return buttonList;
      },
    },
  ];

  const formColums: FormItem[] = [
    { field: 'id', label: 'id', hidden: true },
    { field: 'identification', label: 'identification', hidden: true },
    {
      label: '行业', //表头显示的名称
      field: 'vm', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路
      type: 'select',
      disabled: true,
      options: [
        { value: 1, label: '电子' },
        { value: 2, label: '电池' },
        { value: 3, label: '物流' },
        { value: 4, label: '汽车' },
        { value: 5, label: '太阳能' },
        { value: 6, label: '增材制造' },
        { value: 7, label: '包装' },
        { value: 8, label: '食品饮料' },
        { value: 9, label: '金属加工' },
        { value: 10, label: '其他' },
      ],
    },

    {
      label: '设备名称', //表头显示的名称
      disabled: true,
      field: 'deviceName', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },

    {
      label: '轴名称', //表头显示的名称
      disabled: true,
      field: 'shaftName', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },

    {
      label: '硬件标识符', //表头显示的名称
      disabled: true,
      field: 'hardwareidentifier', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },

    {
      label: '驱动类型', //

      field: 'driveType',
      type: 'select',
      disabled: true,
      options: [
        { value: 1, label: 'V90' },
        { value: 2, label: 'S210' },
      ],
    },
  ];

  const handleSubmit = async () => {
    if (formTitle == '新建驱动参数库') {
      await addDriveParaLib(formRef.current.getFieldsValue());
    } else {
      await updateDriveParaLib(formRef.current.getFieldsValue());
    }

    // message.success('添加成功');
    setFormVisit(false);
    // 这个爆红不用管(从新加载页面)
    actionRef.current.reload();
    message.success('添加成功');
  };
  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable //表格Pro组件
        headerTitle="驱动参数库" //表头
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        // FormRef={editorFormRef}
        // scroll={{ x: 9000 }}
        editable={{
          type: 'multiple',
          onSave: async (rowKey, row) => {
            console.log(row);
            delete row.index;
            if (isCreate) {
              delete row.title;
              delete row.id;
              await addDriveParaLib(row);
            } else {
              await updateDriveParaLib(row);
            }

            actionRef.current.reload();
          },
        }}
        toolBarRender={(action, { selectedRows, selectedRowKeys }) => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              actionRef.current?.addEditRecord?.({
                id: (Math.random() * 1000000).toFixed(0),
                title: '新的一行',
              });
              setIsCreate(true);
            }}
            type="primary"
          >
            新建
          </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          // console.log(params, sort, filter);
          const result = await getDriveParaLibByPage(params);
          console.log(result);
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
          // return  await new Promise({data:[{loginName:}], total:10, success: 0})
          // return {data:[], total:10, success: 0}
        }} //请求数据的地方，例子是用mock模拟数据，我是在后台请求的数据
        columns={columns} //上面定义的
        rowSelection={{}}
      />
    </PageHeaderWrapper>
  );
};

export default DriveParaLib;
